Skip to main content

Creating Custom Constraints

In this example, we create custom constraints, mainly a RigidBody hanging on a rope firmly. We'll also simulate the RigidBody by applying wind forces to it. The final result will look like the following:

rope


Firstly, we require the module and initialize the engine. It is important to set a frame for the canvas if we wish to render constraints on screen.

local canvas = path.to.canvasFrame
local Nature2D = require(game:GetService("ReplicatedStorage").Nature2D)

local viewport = workspace.CurrentCamera.ViewportSize

local Engine = Nature2D.init(path.to.screengui)
Engine:SetPhysicalProperty("CollisionMultiplier", 0.1)
Engine:CreateCanvas(Vector2.new(0, 0), viewport, canvas)

Next, we choose an anchor point, this is the point the rope hangs on from.

local Anchor = Engine:Create("Point", {
Position = Vector2.new(viewport.X/2, 0),
Visible = false,
Snap = true, -- prevent the point from changing positions
KeepInCanvas = false -- or use Anchor:KeepInCanvas(false) instead of the property
})

We then create a RigidBody and connect the anchor and the RigidBody with a constraint.

local RigidBodyFrame = path.to.UIElement
local Body = Engine:Create("RigidBody", {
Object = RigidBodyFrame,
Collidable = true,
Anchored = false
})

local TopLeftCorner = Body:GetVertices()[1]

-- I set the constraint type to be a rope. You can use Rod or Spring as well!
local Rope = Engine:Create("Constraint", {
Type = "Rope",
Point1 = Anchor,
Point2 = TopLeftCorner,
Visible = true,
Thickness = 3,
Color = Color.new(1, 1, 1) -- set constraint color to white (or use Rope:Stroke(Color3.new(1, 1, 1)))
})

We now apply random wind forces to the RigidBody to complete the simulation!

Engine:Start() -- start the simulation

while task.wait() do
local random = Random.new()
Body:ApplyForce(Vector2.new(random:NextNumber(0, 0.5), 0)) -- apply a random wind force
end

There you go! You now have a simulation with custom constraints. These constraints can also be used to connect multiple RigidBodies with each other as well as to create custom RigidBodies and SoftBodies!